package org.jeecg.glr.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import org.jeecg.glr.domain.led.*;
import org.jeecg.glr.entity.GlrColumn;
import org.jeecg.glr.entity.GlrLed;
import org.jeecg.glr.entity.GlrResource;
import org.jeecg.glr.mapper.GlrColumnMapper;
import org.jeecg.glr.mapper.GlrLedMapper;
import org.jeecg.glr.service.IGlrColumnService;
import org.jeecg.glr.service.IGlrLedMemberService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @Description: 栏目内容
 * @Author: jeecg-boot
 * @Date: 2020-02-24
 * @Version: V1.0
 */
@Service
public class GlrColumnServiceImpl extends ServiceImpl<GlrColumnMapper, GlrColumn> implements IGlrColumnService {

    @Resource
    GlrColumnMapper glrColumnMapper;

    @Resource
    IGlrLedMemberService glrLedMemberService;


    @Value("${glr.path.ledServerPath}")
    private String ledServerPath;

    @Value("${glr.path.projectPath}")
    private String projectPath;


    @Resource
    GlrLedMapper glrLedMapper;

    @Override
    public List<GlrLed> getGlrLedByColunmId(String id) {
        return glrColumnMapper.getGlrLedByColunmId(id);
    }

    @Override
    public List<GlrResource> getGlrLedResourceByColunmId(String columnId) {
        return glrColumnMapper.getGlrLedResourceByColunmId(columnId);
    }

    @Override
    public void publishColunm(List<GlrLed> ledCodeList, List<GlrResource> resourceList, String id) {
        final GlrColumn cl = super.getById(id);
        new Thread() {
            @Override
            public void run() {
                int timeSpan = 20;//是播放时长
                if (cl != null) {
                    if (cl.getTimespan() != null && cl.getTimespan() > 0) {
                        timeSpan = cl.getTimespan();
                    }
                }
                for (GlrLed led : ledCodeList) {
                    final String code = led.getCode();
                    if (StringUtil.isNotEmpty(led.getStatus()) && !led.getStatus().equals(GLRConstant.YN_N)) {
                        Gson gson = new Gson();
                        int allSize = 0;
                        int playTime = 0;//是开始播放时间
                        List<Source> sources = new ArrayList<Source>();
                        for (GlrResource resource : resourceList) {
                            Source source = new Source();
                            //如果是视频
                            if (resource.getFileType().toLowerCase().equals(".mp4")) {
                                int filePlayTime = resource.getFilePlayTime();
                                source.set_type("Video");
                                source.setMime("video/mp4");
                                source.setPlayTime(playTime);
                                source.setTimeSpan(filePlayTime);
                                playTime = playTime + filePlayTime;
                            } else {
                                source.set_type("Image");
                                int fixLenght = resource.getFileName().lastIndexOf(".");
                                if (fixLenght != -1) {
                                    String fix = resource.getFileName().substring(fixLenght + 1);
                                    source.setMime("image/" + fix);
                                }
                                source.setPlayTime(playTime);
                                source.setTimeSpan(timeSpan);
                                playTime = playTime + (timeSpan - 1);
                            }
                            source.setId(resource.getFileId());
                            source.setName(resource.getFileId());
                            source.set_id(UUID.randomUUID().toString());
                            source.setMd5(resource.getFileMd5());
                            source.setTop(0);
                            source.setLeft(0);
                            source.setWidth(Integer.parseInt(led.getWidth()));
                            source.setHeight(Integer.parseInt(led.getHeight()));
                            allSize = (int) (allSize + resource.getFileSize());
                            source.setSize(resource.getFileSize());
                            sources.add(source);

                        }
                        List<Layer> layers = new ArrayList<Layer>();
                        Layer layer = new Layer();
                        layer.setSources(sources);
                        layer.setRepeat(false);
                        layers.add(layer);
                        Program p = new Program();
                        p.set_id(UUID.randomUUID().toString());
                        p.setVersion(0);
                        p.setTotalSize(allSize);
                        p.setLayers(layers);
                        p.setWidth(Integer.parseInt(led.getWidth()));
                        p.setHeight(Integer.parseInt(led.getHeight()));
                        List<TaskItem> items = new ArrayList<TaskItem>();
                        TaskItem t = new TaskItem();
                        t.set_id(UUID.randomUUID().toString());
                        t.set_program(p);
                        t.setRepeatTimes(1);

                        List<Schedule> schedules = new ArrayList<Schedule>();
                        Schedule schedule = new Schedule();

                        if(StringUtil.isNotEmpty(cl.getStartTime())){
                            schedule.setStartTime(cl.getStartTime());
                        }else{
                            schedule.setStartTime("00:00");
                        }
                        if(StringUtil.isNotEmpty(cl.getEndTime())){
                            schedule.setEndTime(cl.getEndTime());
                        }else{
                            schedule.setEndTime("23:59");
                        }
                        schedule.setDateType(DateType.All);
                        schedule.setTimeType(TimeType.Range);
                        schedule.setFilterType(FilterType.None);
                        schedules.add(schedule);
                        t.setSchedules(schedules);
                        items.add(t);
                        ProgramsTask pt = new ProgramsTask();
                        pt.set_id(UUID.randomUUID().toString());
                        pt.setItems(items);
                        PlayXixunTaskCommand px = new PlayXixunTaskCommand();
                        px.set_type("PlayXixunTask");
                        final String uuid = UUID.randomUUID().toString();
                        px.setId(uuid);
                        px.setTask(pt);
                        px.setPreDownloadURL(projectPath + GLRConstant.GLR_LED_FILE_PATH+led.getSysCompanyCode()+"/");
                        px.setNotificationURL(projectPath + "glr/glrLed/getByJSON");
                        RequestData rd = new RequestData();
                        rd.set_id(UUID.randomUUID().toString());
                        rd.setCommand(px);
                        final String jsonData = gson.toJson(rd);
                        final String url = ledServerPath + led.getCode(); //check this
                        glrLedMapper.updateCommandId(code, uuid);
                        try {
                            LedCommon.post(url, jsonData);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.start();
    }

    @Override
    public List<GlrLed> getLedCodeByCommonId(String id) {
        return glrColumnMapper.getLedCodeByCommonId(id);
    }

    @Override
    @Transactional
    public void deleteGlrColumnByIds(String ids) {
        List<String> idsList = Arrays.asList(ids.split(","));
        for (String id :
                idsList) {
            super.removeById(id);
            glrLedMemberService.delLedMemberByColumnId(id);
        }

    }
}
